﻿using System;
using PostSharp.Aspects;
using System.Threading;

namespace Framework.Common.AOP.Exceptions
{
    /// <summary>
    /// 重试执行方法
    /// </summary>
    [Serializable]
    public class TryAttribute : OnExceptionAspect
    {
        /// <summary>
        /// 重试次数
        /// </summary>
        public int TryTimes { get; set; }
        /// <summary>
        /// 等待**时间后重试
        /// </summary>
        public int MilliSeconds { get; set; }
        /// <summary>
        /// OnException
        /// </summary>
        /// <param name="args"></param>
        public override void OnException(MethodExecutionArgs args)
        {
            while (TryTimes > 0)
            {
                // Ignore the exception.
                args.FlowBehavior = FlowBehavior.Return;
                if (MilliSeconds > 0) Thread.Sleep(MilliSeconds);
                TryTimes--;
                args.Method.Invoke(args.Instance, args.Arguments.ToArray());
            }
            //while in the last time ,deal the error when invoke the method
            if (TryTimes <= 0)
            {
                string key = Formatter.Format(args);
                LogHelper.Fatal(key, args.Exception);
            }
        }
    }
}
